import { default_project_config } from "@/config";
import { saveUserConfig, getUserConfig, deleteUserConfig } from "./database";

/**
 * 设置用户配置
 * @param userId 用户ID
 * @param configType 配置类型
 * @param configData 配置信息
 * @returns 是否成功
 */
export const setUserConfig = async (
  userId: string,
  configType: string,
  configData: any,
): Promise<boolean> => {
  try {
    return await saveUserConfig(userId, configType, configData);
  } catch (error) {
    console.error("设置用户配置失败:", error);
    return false;
  }
};

/**
 * 获取用户配置
 * @param userId 用户ID
 * @param configType 配置类型
 * @returns 配置信息或null
 */
export const getUserConfigData = async (
  userId: string,
  configType: string,
): Promise<any | null> => {
  try {
    return await getUserConfig(userId, configType);
  } catch (error) {
    console.error("获取用户配置失败:", error);
    return null;
  }
};

/**
 * 删除用户配置
 * @param userId 用户ID
 * @param configType 配置类型
 * @returns 是否成功
 */
export const removeUserConfig = async (
  userId: string,
  configType: string,
): Promise<boolean> => {
  try {
    return await deleteUserConfig(userId, configType);
  } catch (error) {
    console.error("删除用户配置失败:", error);
    return false;
  }
};

// 配置类型枚举
export const CONFIG_TYPES = {
  PROJECT_NAME: "project-name",
  CANVAS: "canvas",
  TEXT_BASIC: "text-basic",
  TEXT_BORDER: "text-border",
  TEXT_BACKGROUND: "text-background",
  TEXT_ANIMATION: "text-animation",
  VIDEO_MATERIALS: "video-materials",
  TEXT_COLORS: "text-colors", // 新增文本颜色配置
  ANIMATION_SETTINGS: "text-animation-settings", // 新增动画设置配置
  AUDIO_MATERIAL: "audio-material", // 音频素材配置
  // 文本在画布中的位置
  TEXT_POSITION: "text_position",
} as const;

// 配置类型定义
export interface UserConfig {
  canvas?: {
    width: number;
    height: number;
    fps: number;
  };
  textBasic?: {
    content: string;
    startTime: number;
    duration: number;
    fontSize: number;
    color: string;
    isBold: boolean;
    isItalic: boolean;
    isUnderline: boolean;
    opacity: number;
    align: number;
    letterSpacing: number;
    lineSpacing: number;
  };
  textBorder?: {
    color: string;
    width: number;
    opacity: number;
  };
  textBackground?: {
    color: string;
    style: number;
    opacity: number;
    width: number;
    height: number;
    horizontalOffset: number;
    verticalOffset: number;
    roundRadius: number;
  };
  textAnimation?: {
    introAnimation: string;
    outroAnimation: string;
    loopAnimation: string;
    introDuration: number;
    outroDuration: number;
  };
  videoMaterials?: Array<{
    track_name: string;
    start_time: number;
    duration: number;
    relative_index: number;
    material: {
      path: string;
      name: string;
      crop_settings: any;
    };
  }>;
  textColors?: {
    textColor: string;
    borderColor: string;
    backgroundColor: string;
  };
  animationSettings?: {
    introAnimation: string;
    outroAnimation: string;
    loopAnimation: string;
  };
}

/**
 * 保存特定类型的用户配置
 * @param userId 用户ID
 * @param configType 配置类型
 * @param configData 配置数据
 * @returns 是否成功
 */
export const saveSpecificUserConfig = async (
  userId: string,
  configType: keyof typeof CONFIG_TYPES | string,
  configData: any,
): Promise<boolean> => {
  try {
    return await saveUserConfig(userId, configType, configData);
  } catch (error) {
    console.error(`保存${configType}配置失败:`, error);
    return false;
  }
};

/**
 * 获取特定类型的用户配置
 * @param userId 用户ID
 * @param configType 配置类型
 * @returns 配置数据或null
 */
export const getSpecificUserConfig = async (
  userId: string,
  configType: keyof typeof CONFIG_TYPES | string,
): Promise<any | null> => {
  try {
    return await getUserConfig(userId, configType);
  } catch (error) {
    console.error(`获取${configType}配置失败:`, error);
    return null;
  }
};

/**
 * 获取完整的用户配置
 * @param userId 用户ID
 * @returns 完整配置对象
 */
export const getFullUserConfig = async (
  userId: string,
): Promise<VideoProjectConfig> => {
  const config: VideoProjectConfig = default_project_config;

  try {
    // 并行获取所有配置类型
    const [
      canvas,
      textBasic,
      textBorder,
      textBackground,
      textAnimation,
      videoMaterials,
      textColors,
      animationSettings,
      textPosition,
    ] = await Promise.all([
      getSpecificUserConfig(userId, CONFIG_TYPES.CANVAS),
      getSpecificUserConfig(userId, CONFIG_TYPES.TEXT_BASIC),
      getSpecificUserConfig(userId, CONFIG_TYPES.TEXT_BORDER),
      getSpecificUserConfig(userId, CONFIG_TYPES.TEXT_BACKGROUND),
      getSpecificUserConfig(userId, CONFIG_TYPES.TEXT_ANIMATION),
      getSpecificUserConfig(userId, CONFIG_TYPES.VIDEO_MATERIALS),
      getSpecificUserConfig(userId, CONFIG_TYPES.TEXT_COLORS),
      getSpecificUserConfig(userId, CONFIG_TYPES.ANIMATION_SETTINGS),
      getSpecificUserConfig(userId, CONFIG_TYPES.TEXT_POSITION),
    ]);

    if (canvas) config.canvas = canvas;
    if (textBasic) config.textBasic = textBasic;
    if (textBorder) config.textBorder = textBorder;
    if (textBackground) config.textBackground = textBackground;
    if (textAnimation) config.textAnimation = textAnimation;
    if (videoMaterials) config.videoMaterials = videoMaterials;
    if (textColors) config.textColors = textColors;
    if (animationSettings) config.textAnimationSettings = animationSettings;
    if (textPosition) config.textPosition = textPosition;

    return config;
  } catch (error) {
    console.error("获取完整用户配置失败:", error);
    return config;
  }
};

/**
 * 保存文本颜色配置
 * @param userId 用户ID
 * @param textColor 文本颜色
 * @param borderColor 边框颜色
 * @param backgroundColor 背景颜色
 * @returns 是否成功
 */
export const saveTextColors = async (
  userId: string,
  textColor: string,
  borderColor: string,
  backgroundColor: string,
): Promise<boolean> => {
  try {
    const colorConfig = {
      textColor,
      borderColor,
      backgroundColor,
    };
    return await saveSpecificUserConfig(
      userId,
      CONFIG_TYPES.TEXT_COLORS,
      colorConfig,
    );
  } catch (error) {
    console.error("保存文本颜色配置失败:", error);
    return false;
  }
};

/**
 * 保存动画设置配置
 * @param userId 用户ID
 * @param introAnimation 入场动画
 * @param outroAnimation 出场动画
 * @param loopAnimation 循环动画
 * @returns 是否成功
 */
export const saveAnimationSettings = async (
  userId: string,
  introAnimation: string,
  outroAnimation: string,
  loopAnimation: string,
): Promise<boolean> => {
  try {
    const animationConfig = {
      introAnimation,
      outroAnimation,
      loopAnimation,
    };
    return await saveSpecificUserConfig(
      userId,
      CONFIG_TYPES.ANIMATION_SETTINGS,
      animationConfig,
    );
  } catch (error) {
    console.error("保存动画设置配置失败:", error);
    return false;
  }
};

/**
 * 从存储中构建完整的预览/项目数据
 * @param userId 用户ID
 * @returns 构建的项目数据
 */
export const buildProjectDataFromStorage = async (
  userId: string,
): Promise<any> => {
  try {
    const savedConfig = await getFullUserConfig(userId);

    // 颜色转换函数
    const hexToRgb = (hex: string): number[] => {
      const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
      return result
        ? [
          parseInt(result[1], 16) / 255,
          parseInt(result[2], 16) / 255,
          parseInt(result[3], 16) / 255,
        ]
        : [1, 1, 1];
    };

    // 构建项目数据
    const projectData = {
      canvas_config: {
        width: savedConfig.canvas?.width || 1920,
        height: savedConfig.canvas?.height || 1080,
        fps: savedConfig.canvas?.fps || 30,
      },
      text_conf: {
        text: savedConfig.textBasic?.content || "生活是美好的，也是残酷的",
        start_time: (savedConfig.textBasic?.startTime || 1) * 1000000,
        duration: (savedConfig.textBasic?.duration || 8) * 1000000,
        style: {
          size: savedConfig.textBasic?.fontSize || 12,
          bold: savedConfig.textBasic?.isBold || false,
          italic: savedConfig.textBasic?.isItalic || false,
          underline: savedConfig.textBasic?.isUnderline || false,
          color: hexToRgb(
            savedConfig.textColors?.textColor ||
            savedConfig.textBasic?.color ||
            "#ffffff",
          ),
          align: savedConfig.textBasic?.align || 1,
          opacity: savedConfig.textBasic?.opacity || 0.95,
          letter_spacing: savedConfig.textBasic?.letterSpacing || 5,
          line_spacing: savedConfig.textBasic?.lineSpacing || 8,
        },
        border: {
          color: hexToRgb(
            savedConfig.textColors?.borderColor ||
            savedConfig.textBorder?.color ||
            "#000000",
          ),
          width: savedConfig.textBorder?.width || 45,
          opacity: savedConfig.textBorder?.opacity || 0.8,
        },
        background: {
          color:
            savedConfig.textColors?.backgroundColor ||
            savedConfig.textBackground?.color ||
            "#000000",
          style: savedConfig.textBackground?.style || 2,
          opacity: savedConfig.textBackground?.opacity || 0.7,
          width: savedConfig.textBackground?.width || 0.4,
          height: savedConfig.textBackground?.height || 0.2,
          horizontal_offset:
            savedConfig.textBackground?.horizontalOffset || 0.5,
          vertical_offset: savedConfig.textBackground?.verticalOffset || 0.6,
        },
        animations: {
          intro: {
            type:
              savedConfig.textAnimationSettings?.introAnimation ||
              savedConfig.textAnimation?.introAnimation ||
              "渐显",
            duration:
              (savedConfig.textAnimation?.introDuration || 1.5) * 1000000,
          },
          outro: {
            type:
              savedConfig.textAnimationSettings?.outroAnimation ||
              savedConfig.textAnimation?.outroAnimation ||
              "渐隐",
            duration: (savedConfig.textAnimation?.outroDuration || 1) * 1000000,
          },
          loop: {
            type:
              savedConfig.textAnimationSettings?.loopAnimation ||
              savedConfig.textAnimation?.loopAnimation ||
              "跳动",
          },
        },
      },
      video_conf: {
        video_materials: savedConfig.videoMaterials || [],
      },
    };

    return projectData;
  } catch (error) {
    console.error("从存储构建项目数据失败:", error);
    throw error;
  }
};
